﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using AutoBuildEntity.Common;
using AutoBuildEntity.Model;

namespace AutoBuildEntity
{
    /// <summary>
    ///     UserWindow.xaml 的交互逻辑
    /// </summary>
    public partial class UserWindow : Window
    {
        /// <summary>
        ///     命名空间
        /// </summary>
        public string NameSpace { get; }

        /// <summary>
        ///     模板及配置信息
        /// </summary>
        public string EntityXmlPath { get; }

        /// <summary>
        ///     文件保存地址
        /// </summary>
        public string FileSavePath { get; }

        private List<ComboBoxItem> _comboBoxData = new List<ComboBoxItem>();
        private List<TableColumnModel> _tables = new List<TableColumnModel>();
        private List<TableColumnModel> _views = new List<TableColumnModel>();
        private readonly List<ComboBoxItem> _dataBaseTableNames = new List<ComboBoxItem>();
        private readonly List<ComboBoxItem> _dataBaseViewNames = new List<ComboBoxItem>();
        public EntityXml EntityXml { get; set; }

        private DataContext _dataBaseContext;

        public UserWindow(string nameSpace, string entityXmlPath, string filePath)
        {
            NameSpace = nameSpace;
            EntityXmlPath = entityXmlPath;
            FileSavePath = filePath;
            EntityXml = new EntityXml($"{entityXmlPath}\\{EntityXml.EntityXmlName}");
            EntityXml.Load();
            InitializeComponent();
            InitData();
        }

        private void InitData()
        {
            //CbType.ItemsSource = new List<ComboBoxItem>
            //{
            //    new ComboBoxItem {Id = 1, Name = "表"},
            //    new ComboBoxItem {Id = 2, Name = "视图"}
            //};
            if (!string.IsNullOrEmpty(EntityXml.MySqlConnString))
            {
                _dataBaseContext = new DataContext(EntityXml.MySqlConnString, DataBaseType.MySql);
            }
            else
            {
                if (!string.IsNullOrEmpty(EntityXml.MsSqlConnString))
                    _dataBaseContext = new DataContext(EntityXml.MySqlConnString, DataBaseType.MsSql);
                else
                    ShowMsg("请配置数据库连接方式");
            }

            try
            {
                _tables = _dataBaseContext.GetTableColumn();
                TableColumnHelper.ConvertToCs(_tables);
                foreach (var item in _tables.Distinct())
                    if (_dataBaseTableNames.FirstOrDefault(x => x.Name == item.TableName) == null)
                        _dataBaseTableNames.Add(new ComboBoxItem {Name = item.TableName});

                _comboBoxData = _dataBaseTableNames;
                TableNames.ItemsSource = _comboBoxData;
            }
            catch (Exception e)
            {
                ShowMsg(e.Message);
            }
        }

        private void TableNames_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            TableNames.ItemsSource = _comboBoxData.Where(x => x.Name.Contains(TableNames.Text)).ToList();
            TableNames.IsDropDownOpen = true;
        }

        private void CbType_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if(CbType.SelectedValue is System.Windows.Controls.ComboBoxItem selectedValue)
            {
                if (selectedValue.Content != null && selectedValue.Content.Equals("视图"))
                {
                    if (_views.Count == 0)
                    {
                        _views = _dataBaseContext.GetViewColumn();
                        TableColumnHelper.ConvertToCs(_views);
                        foreach (var item in _views.Distinct())
                            if (_dataBaseViewNames.FirstOrDefault(x => x.Name == item.TableName) == null)
                                _dataBaseViewNames.Add(new ComboBoxItem { Name = item.TableName });

                        _comboBoxData = _dataBaseViewNames;
                        TableNames.ItemsSource = _comboBoxData;
                    }
                }
            }
        }

        private void ShowMsg(string msg)
        {
            MessageBox.Show(msg);
            IsEnabled = false;
            Close();
        }

        private void BtnModel_Click(object sender, RoutedEventArgs e)
        {
            if (TableNames.SelectedValue is ComboBoxItem selectedValue)
            {
                var entityName = TableColumnHelper.UpperEveryWord(selectedValue.Name);
                var columns = _tables.Where(x => x.TableName == selectedValue.Name).ToList();
                var result = NVelocityHelper.ProcessTemplate(EntityXml.EntityTemplate,
                    new TemplateModel(entityName, columns, NameSpace));
                Clipboard.SetDataObject(result);
                Write(FileSavePath, entityName, result);
            }
        }

        private void BtnSelect_Click(object sender, RoutedEventArgs e)
        {
            ChangeStackPanel(false);
        }


        private void BtnSelectOk_Click(object sender, RoutedEventArgs e)
        {
            if (TableNames.SelectedValue is ComboBoxItem selectedValue)
            {
                var columns = _tables.Where(x => x.TableName == selectedValue.Name).ToList();
                var result = _dataBaseContext.GetSql(columns, selectedValue.Name, TxtAlias.Text?.Trim());
                if (!string.IsNullOrEmpty(result))
                {
                    TbShowSelect.Text = result;
                    Clipboard.Clear();
                    Clipboard.SetDataObject(result,true);
                }
            }

            ChangeStackPanel(true);
        }

        private void BtnSelectCancel_Click(object sender, RoutedEventArgs e)
        {
            ChangeStackPanel(true);
        }

        private string Write(string directory, string fileName, string content)
        {
            var newFileName = CbDo.IsChecked == true ? $"{fileName}Do" : fileName;
            var path = Path.Combine(directory, newFileName + ".cs");
            if (File.Exists(path))
            {
                var result = MessageBox.Show(this, $"{newFileName}已存在,是否覆盖？(生成的内容已经存在粘贴板)", "提示", MessageBoxButton.YesNo,
                    MessageBoxImage.Warning);
                if (result == MessageBoxResult.No || result == MessageBoxResult.None)
                    return path;
            }

            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                var byteFile = Encoding.UTF8.GetBytes(content);
                fs.Write(byteFile, 0, byteFile.Length);
            }

            return path;
        }

        private void ChangeStackPanel(bool isBase)
        {
            if (isBase)
            {
                SpBase.Visibility = Visibility.Visible;
                SpAlias.Visibility = Visibility.Hidden;
            }
            else
            {
                SpBase.Visibility = Visibility.Hidden;
                SpAlias.Visibility = Visibility.Visible;
            }
        }
    }

    internal class ComboBoxItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}